package com.ltu.util.ext.kaptcha;

import com.google.code.kaptcha.Constants;
import com.ltu.constant.CommonConstant;
import com.ltu.util.common.StrUtils;
import com.ltu.util.redis.RedistUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.sql.Struct;

@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class KaptchaUtil {

    private final RedistUtil redistUtil;

    public static RedistUtil redis;

    @PostConstruct
    public void init() {
        redis = redistUtil;
    }

    /**
     * 将获取到的前端参数转为string类型
     * @param request
     * @param key
     * @return
     */
    public static String getString(HttpServletRequest request, String key) {
        try {
            String result = request.getParameter(key);
            if(result != null) {
                result = result.trim();
            }
            if("".equals(result)) {
                result = null;
            }
            return result;
        }catch(Exception e) {
            return null;
        }
    }
    /**
     * 验证码校验，uuid可为null
     * @param verifyCodeActual
     * @param uuid
     * @return
     */
    public static boolean checkVerifyCode(String verifyCodeActual, String uuid) {
        String verifyCodeExpected = "";
        if (StrUtils.isTrimNull(uuid)) {
            //Session的方式
            Session session = SecurityUtils.getSubject().getSession();
            //获取生成的验证码
            verifyCodeExpected = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
            session.removeAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        }
        else {
            //UUID的方式
            //获取生成的验证码
            verifyCodeExpected = (String)redis.getValue(CommonConstant.KAPTCHA_REDIS_DEFAULT_PREFIX+uuid);
            redis.removeKey(CommonConstant.KAPTCHA_REDIS_DEFAULT_PREFIX+uuid);
        }
        log.info("Input:" + verifyCodeActual + ";Expect:" + verifyCodeExpected);
        //校验
        if(StrUtils.isTrimNull(verifyCodeActual) || !verifyCodeActual.equals(verifyCodeExpected)) {
            return false;
        }
        return true;
    }
}
